Skip to content

fix(drivers): read every Snowflake private-key format - #1777

Merged
hkaltai merged 4 commits into
mainfrom
fix/snowflake-key-formats
Nov 19, 2026
Merged

hkaltai merged 4 commits into
mainfrom
fix/snowflake-key-formats

Conversation

@hkaltai

@hkaltai hkaltai commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Issue for this PR

Closes #

Type of change

  • Bug fix
  • New feature
  • Refactor / code improvement
  • Documentation

What does this PR do?

The local Snowflake driver's key-pair handling only decrypted keys when a passphrase was set or the text contained "ENCRYPTED", and only normalized literal \n. PEMs whose line breaks became spaces, encrypted PKCS#8 keys without a passphrase, and legacy encrypted PKCS#1 keys (Proc-Type/DEK-Info) failed with raw OpenSSL errors such as 1E08010C:DECODER routines::unsupported.

The key handling now lives in packages/drivers/src/snowflake-key.ts: it strips surrounding quotes, converts literal \n, CRLF and space-separated bodies back to 64-char lines between the BEGIN/END markers (keeping legacy headers on their own lines), then converts any supported key (unencrypted PKCS#1/PKCS#8, encrypted PKCS#8, legacy-encrypted PKCS#1) to unencrypted PKCS#8 for the SDK. A missing passphrase gives "key is encrypted; set the passphrase", a wrong passphrase or unparseable key gives a fixed message; no key material or OpenSSL text is included.

How did you verify your code works?

New packages/drivers/test/snowflake-key.test.ts generates keys at test time with node:crypto for each format and variant (multiline, CRLF, space-separated, \n-escaped, quoted), plus error cases and connect() wiring. The connect() tests fail on origin/main. bun typecheck and the snowflake driver tests pass.

Cost side effects

None.

Screenshots / recordings

N/A

Checklist

  • I have tested my changes locally
  • I have not included unrelated changes in this PR
  • I checked for cost side effects (model calls, queries or cloud resources that grow with user data) and described them, or wrote "none"

Summary by cubic

Makes the Snowflake driver accept every common private-key format, so key-pair auth no longer fails on formatting quirks like escaped newlines, quotes, CRLF, or space-separated bodies.

  • Normalizes pasted PEMs (quotes, literal \n sequences, space-joined bodies, CRLF) back to canonical 64-char-line form.
  • Finds the private key even when other PEM blocks (certificates, public keys) come first.
  • Converts unencrypted PKCS#1/RSA and SEC1 keys, encrypted PKCS#8, and legacy-encrypted PKCS#1 (Proc-Type/DEK-Info) to unencrypted PKCS#8 for snowflake-sdk.
  • A missing or wrong private_key_passphrase now raises a clear, actionable error without echoing key material or OpenSSL internals.
  • Moves key handling into snowflake-key.ts with a test suite covering every format and variant.

Written for commit 7c5c792. Summary will update on new commits.

View guided diff Turn on auto-fix

Summary by CodeRabbit

  • New Features
    • Snowflake key-pair authentication supports private keys with varied quoting, whitespace, and newline formats, as well as supported encrypted key formats.
    • Encrypted keys require a passphrase. Error messages distinguish missing passphrases from invalid or unsupported key input without revealing key contents.
  • Bug Fixes
    • Supported private keys are converted into the format required for Snowflake authentication, improving compatibility with pasted key formats.

Normalize pasted PEMs (quotes, literal \n, space-separated bodies, CRLF) and
convert unencrypted PKCS#1/PKCS#8, encrypted PKCS#8 and legacy-encrypted PKCS#1
keys to PKCS#8. A missing or wrong passphrase now gives an actionable error
without key material.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Explain Change →

Warning

Review limit reached

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Next included review available in 13 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

Learn how review limits work.

Review configuration:

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 73f7fbb6-914b-468c-9bcc-f3f81d1d9a1f
Commits

Reviewing files that changed from the base of the PR and between 61c7e51 and 7c5c792.

Files selected for processing: 2

  • packages/drivers/src/snowflake-key.ts
  • packages/drivers/test/snowflake-key.test.ts

No actionable comments were generated in the recent review.

Walkthrough

The Snowflake driver now normalizes private-key PEM input and converts supported keys to unencrypted PKCS#8 before JWT authentication. Tests cover PEM formats, encryption and passphrase errors, and connection wiring.

Changes: Snowflake key-pair authentication

Layer / File(s) Summary
Private-key normalization and conversion
packages/drivers/src/snowflake-key.ts, packages/drivers/test/snowflake-key.test.ts
New helpers normalize PEM formatting and convert supported private keys to unencrypted PKCS#8. Tests cover key formats, encrypted inputs, error handling, and normalization behavior.
Snowflake connection integration
packages/drivers/src/snowflake.ts, packages/drivers/test/snowflake-key.test.ts
The connection setup calls toPkcs8Pem before passing key content to the SDK. Tests check the resulting key and behavior when an encrypted key has no passphrase.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant SnowflakeConnect
  participant toPkcs8Pem
  participant SnowflakeSDK
  SnowflakeConnect->>toPkcs8Pem: Convert keyContent with keyPassphrase
  toPkcs8Pem-->>SnowflakeConnect: Return unencrypted PKCS#8 PEM
  SnowflakeConnect->>SnowflakeSDK: Pass key with JWT authenticator
Loading

Suggested reviewers: sahrizvi

Merge Risk: Minimal · previous review 61c7e

This change makes Snowflake key-pair authentication accept more private-key formats and formatting variants, and it reports clear errors for missing or wrong passphrases. No actionable merge-blocking risk was found.

Pre-merge checks: Passed 4

Check name Status Explanation
Title check Passed The title "fix(drivers): read every Snowflake private-key format" names the main change: the Snowflake driver now accepts all common private-key formats. It follows conventional-commit style and is sp…
Description check Passed The description follows the repository template. It marks the Bug fix type, explains the root cause and the fix, and describes how the change was verified with new tests. It includes the cost side-eff…
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Full details: Title check

Explanation

The title "fix(drivers): read every Snowflake private-key format" names the main change: the Snowflake driver now accepts all common private-key formats. It follows conventional-commit style and is specific enough for a reader scanning history. The title does not mention the new snowflake-key.ts module, but that detail is not required.

Full details: Description check

Explanation

The description follows the repository template. It marks the Bug fix type, explains the root cause and the fix, and describes how the change was verified with new tests. It includes the cost side-effects section with 'None', and the checklist is filled in. The 'Issue for this PR' section still reads 'Closes #' without an issue number. The description also contains an auto-generated cubic summary block, which the template does not require. Those points are minor.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
Fix failing CI checks

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

A rabbit checks the PEM in rows,
Then wraps each line and onward goes.
The key is shaped for JWT flight,
With passphrase errors clear and right.
The SDK receives the PKCS#8 light.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: f36bd659-9b85-492f-ba81-c7c79debf1f8
Commits

Reviewing files that changed from the base of the PR and between bdb87a8 and 61c7e51.

Files selected for processing: 2

  • packages/drivers/src/snowflake-key.ts
  • packages/drivers/test/snowflake-key.test.ts

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 0 remain after this review.

@github-actions

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

This PR doesn't fully meet our contributing guidelines and PR template.

What needs to be fixed:

  • No issue referenced. Please add Closes #<number> linking to the relevant issue.

Please edit this PR description to address the above within 2 hours, or it will be automatically closed.

If you believe this was flagged incorrectly, please let a maintainer know.

@github-actions

Copy link
Copy Markdown

Thanks for your contribution!

This PR doesn't have a linked issue. All PRs must reference an existing issue.

Please:

  1. Open an issue describing the bug/feature (if one doesn't exist)
  2. Add Fixes #<number> or Closes #<number> to this PR description

See CONTRIBUTING.md for details.

@hkaltai
hkaltai marked this pull request as ready for review November 19, 2026 13:49
Comment thread packages/drivers/src/snowflake-key.ts Outdated

import * as crypto from "crypto"

const PEM_BLOCK = /-----BEGIN ([A-Z0-9 ]+?)-----([\s\S]*?)-----END \1-----/

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

WARNING: PEM_BLOCK takes the first BEGIN/END block in the text regardless of its label, and toPkcs8Pem then rejects it if the label is not a private-key label. A multi-block PEM file where a non-key block comes first (e.g. a certificate chain followed by the private key, or a public key above the private key) is therefore reported as format is not recognized and the connection fails.

That input previously worked: connect() passed unencrypted key text through verbatim and OpenSSL's PEM reader skips non-matching blocks until it finds the private key. Matching a private-key label explicitly keeps that behavior while still rejecting public-only PEMs (the not recognized path).

Suggested change
const PEM_BLOCK = /-----BEGIN ([A-Z0-9 ]+?)-----([\s\S]*?)-----END \1-----/
const PEM_BLOCK = /-----BEGIN ((?:ENCRYPTED |RSA |EC )?PRIVATE KEY)-----([\s\S]*?)-----END \1-----/

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 61c7e51: the parser now scans every PEM block and uses the first private-key block, with tests for a public key placed before plain and encrypted private keys.

@kilo-code-bot

kilo-code-bot Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Code Review Summary

Status: No Issues Found | Recommendation: Merge

Incremental review of ea3d60b..7c5c792: the redaction test now collects the base64 body lines and asserts the set is non-empty before checking them, so the leak check can no longer pass vacuously. The prior SUGGESTION on that test is resolved at this HEAD.

Files Reviewed (2 files)
  • packages/drivers/test/snowflake-key.test.ts - no issues (incremental change: non-empty assertion added before the redaction loop)
  • packages/drivers/src/snowflake-key.ts - no issues (re-verified private-key label matching, legacy header handling, and password/decrypt error paths)
Previous Review Summaries (3 snapshots, latest commit ea3d60b)

Current summary above is authoritative. Previous snapshots are kept for context only.

Previous review (commit ea3d60b)

Status: 1 Issue Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 0
SUGGESTION 1
Issue Details (click to expand)

SUGGESTION

File Line Issue
packages/drivers/test/snowflake-key.test.ts 68 The redaction loop passes vacuously when the base64-line filter matches nothing; assert the filtered set is non-empty so the leak check cannot silently become a no-op.
Files Reviewed (2 files)
  • packages/drivers/src/snowflake-key.ts - no issues (the redundant ?? text.match(...) fallback from the previous review is removed, and matching still returns undefined for public-only PEMs so toPkcs8Pem keeps reporting not recognized)
  • packages/drivers/test/snowflake-key.test.ts - 1 issue

The prior WARNING (non-key block before the private key) and the prior SUGGESTION (unreachable fallback) are both fixed at this HEAD.

Fix these issues in Kilo Cloud

Previous review (commit 61c7e51)

Status: 1 Issue Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 0
SUGGESTION 1
Issue Details (click to expand)

SUGGESTION

File Line Issue
packages/drivers/src/snowflake-key.ts 41 The ?? text.match(new RegExp(PEM_BLOCK.source)) fallback is unreachable in effect: when find fails, no block is a private key, so the fallback returns a block that toPkcs8Pem rejects with the same not recognized error. Dropping it also matches the new comment and avoids recompiling the regex per call.
Files Reviewed (2 files)
  • packages/drivers/src/snowflake-key.ts - 1 issue
  • packages/drivers/test/snowflake-key.test.ts - no issues

Previous review's WARNING (multi-block PEM where a non-key block precedes the private key) is fixed: the parser now scans all blocks, selects the first private-key label, and the new test covers a public key placed before plain and encrypted private keys.

Fix these issues in Kilo Cloud

Previous review (commit bdb87a8)

Status: 1 Issue Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 1
SUGGESTION 0
Issue Details (click to expand)

WARNING

File Line Issue
packages/drivers/src/snowflake-key.ts 14 PEM_BLOCK picks the first BEGIN/END block regardless of label, so a multi-block PEM where a certificate/public key precedes the private key is now rejected as "not recognized". Previously such unencrypted files were passed through verbatim and OpenSSL skipped to the private-key block. Match a private-key label explicitly.
Files Reviewed (3 files)
  • packages/drivers/src/snowflake-key.ts - 1 issue
  • packages/drivers/src/snowflake.ts - no issues
  • packages/drivers/test/snowflake-key.test.ts - no issues

Fix these issues in Kilo Cloud


Reviewed by deepseek-v4.1-flash-1017 · Input: 0 · Output: 0 · Cached: 0

Review guidance: REVIEW.md from base branch main

@hkaltai

hkaltai commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

review-loop: APPROVED at bdb87a8 (reviewers: gpt-6-astra high, gpt-6.1-sol high)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Comment thread packages/drivers/src/snowflake-key.ts Outdated

// A pasted file may hold other blocks (certificates, public key) before the
// private key; use the first block that is a private key.
const match = [...text.matchAll(PEM_BLOCK)].find((m) => /PRIVATE KEY$/.test(m[1])) ?? text.match(new RegExp(PEM_BLOCK.source))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Redundant fallback can be dropped

find returns undefined only when no block's label ends in PRIVATE KEY, so ?? text.match(new RegExp(PEM_BLOCK.source)) re-reads the first block, which toPkcs8Pem then rejects with the same not recognized error through its label check. The fallback therefore never changes observable behavior; it only recompiles the regex on every call and contradicts the comment above it ("use the first block that is a private key").

Suggested change
const match = [...text.matchAll(PEM_BLOCK)].find((m) => /PRIVATE KEY$/.test(m[1])) ?? text.match(new RegExp(PEM_BLOCK.source))
const match = [...text.matchAll(PEM_BLOCK)].find((m) => /PRIVATE KEY$/.test(m[1]))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ea3d60b: the fallback is removed.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 3 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="packages/drivers/src/snowflake-key.ts">

<violation number="1" location="packages/drivers/src/snowflake-key.ts:95">
P2: `toPkcs8Pem` accepts any private key that Node can parse, including EC/DSA keys and RSA keys smaller than 2048 bits. Snowflake key-pair authentication requires at least a 2048-bit RSA key, so these inputs reach `SNOWFLAKE_JWT` and fail later in the SDK; validate `asymmetricKeyType` and `modulusLength` before exporting.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Turn on auto-fix | Re-trigger cubic

Comment on lines +95 to +109
try {
const keyObject = crypto.createPrivateKey({ key: normalized.pem, format: "pem", passphrase: pass })
return keyObject.export({ type: "pkcs8", format: "pem" }).toString()
} catch {
if (encrypted) {
throw new Error(
"Snowflake: failed to decrypt the private key. The passphrase (private_key_passphrase) is incorrect, " +
"or the key is corrupted or uses an unsupported cipher.",
)
}
throw new Error(
"Snowflake private key could not be parsed. It may be truncated, corrupted, or in an unsupported format; " +
"use an RSA key in PKCS#8 or PKCS#1 PEM form.",
)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: toPkcs8Pem accepts any private key that Node can parse, including EC/DSA keys and RSA keys smaller than 2048 bits. Snowflake key-pair authentication requires at least a 2048-bit RSA key, so these inputs reach SNOWFLAKE_JWT and fail later in the SDK; validate asymmetricKeyType and modulusLength before exporting.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/drivers/src/snowflake-key.ts, line 95:

<comment>`toPkcs8Pem` accepts any private key that Node can parse, including EC/DSA keys and RSA keys smaller than 2048 bits. Snowflake key-pair authentication requires at least a 2048-bit RSA key, so these inputs reach `SNOWFLAKE_JWT` and fail later in the SDK; validate `asymmetricKeyType` and `modulusLength` before exporting.</comment>

<file context>
@@ -0,0 +1,110 @@
+    )
+  }
+
+  try {
+    const keyObject = crypto.createPrivateKey({ key: normalized.pem, format: "pem", passphrase: pass })
+    return keyObject.export({ type: "pkcs8", format: "pem" }).toString()
</file context>
Suggested change
try {
const keyObject = crypto.createPrivateKey({ key: normalized.pem, format: "pem", passphrase: pass })
return keyObject.export({ type: "pkcs8", format: "pem" }).toString()
} catch {
if (encrypted) {
throw new Error(
"Snowflake: failed to decrypt the private key. The passphrase (private_key_passphrase) is incorrect, " +
"or the key is corrupted or uses an unsupported cipher.",
)
}
throw new Error(
"Snowflake private key could not be parsed. It may be truncated, corrupted, or in an unsupported format; " +
"use an RSA key in PKCS#8 or PKCS#1 PEM form.",
)
}
let keyObject: crypto.KeyObject
try {
keyObject = crypto.createPrivateKey({ key: normalized.pem, format: "pem", passphrase: pass })
} catch {
if (encrypted) {
throw new Error(
"Snowflake: failed to decrypt the private key. The passphrase (private_key_passphrase) is incorrect, " +
"or the key is corrupted or uses an unsupported cipher.",
)
}
throw new Error(
"Snowflake private key could not be parsed. It may be truncated, corrupted, or in an unsupported format; " +
"use an RSA key in PKCS#8 or PKCS#1 PEM form.",
)
}
const modulusLength = keyObject.asymmetricKeyDetails?.modulusLength ?? 0
if (keyObject.asymmetricKeyType !== "rsa" || modulusLength < 2048) {
throw new Error("Snowflake private key must be an RSA key with at least 2048 bits.")
}
return keyObject.export({ type: "pkcs8", format: "pem" }).toString()

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not changing this here: the issue is about reading pasted formats, and rejecting other key types or sizes could break keys that work today. The SDK and Snowflake already report an unsupported key type or size when connecting.

@hkaltai

hkaltai commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

review-loop: APPROVED at 61c7e51 (reviewers: gpt-6-astra high, gpt-6.1-sol high)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
}
expect(msg).toMatch(/passphrase .* incorrect/)
expect(msg).not.toMatch(/DECODER|bad decrypt|wrong/)
for (const line of pem.split("\n").filter((l) => /^[A-Za-z0-9+/=]{40,}$/.test(l))) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SUGGESTION: Guard the redaction assertion against an empty match set

This loop only proves anything when the filter matches at least one body line. If the PEM layout ever changes (a shorter final line, an unwrapped body, a cipher with different line lengths), the filtered list is empty and the test passes without checking anything, silently losing the leak protection this test exists for.

Collect the lines first and assert the set is non-empty before looping, e.g. const lines = pem.split("\n").filter(...) then expect(lines.length).toBeGreaterThan(0) before for (const line of lines) expect(msg).not.toContain(line).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 7c5c792: the test asserts that ciphertext body lines were found before checking them.

@hkaltai

hkaltai commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

review-loop: APPROVED at ea3d60b (reviewers: gpt-6-astra high, gpt-6.1-sol high)

@dev-punia-altimate dev-punia-altimate left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 Code Review — OpenCodeReview (Gemini) — 1 finding(s)

  • 1 anchored to a line (posted inline when the comment stream is on)
  • 0 without a line anchor
All findings (full text)

1. packages/drivers/src/snowflake-key.ts (L41)

[🟠 MEDIUM] Since matchAll already finds all matches in the text, you can avoid re-instantiating a new RegExp and re-scanning the string by reusing the matches array. This is more efficient and cleaner.

Suggested change:

  const matches = [...text.matchAll(PEM_BLOCK)]
  const match = matches.find((m) => /PRIVATE KEY$/.test(m[1])) ?? matches[0]

Comment thread packages/drivers/src/snowflake-key.ts Outdated

// A pasted file may hold other blocks (certificates, public key) before the
// private key; use the first block that is a private key.
const match = [...text.matchAll(PEM_BLOCK)].find((m) => /PRIVATE KEY$/.test(m[1])) ?? text.match(new RegExp(PEM_BLOCK.source))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[🟠 MEDIUM] Since matchAll already finds all matches in the text, you can avoid re-instantiating a new RegExp and re-scanning the string by reusing the matches array. This is more efficient and cleaner.

Suggested change:

Suggested change
const match = [...text.matchAll(PEM_BLOCK)].find((m) => /PRIVATE KEY$/.test(m[1])) ?? text.match(new RegExp(PEM_BLOCK.source))
const matches = [...text.matchAll(PEM_BLOCK)]
const match = matches.find((m) => /PRIVATE KEY$/.test(m[1])) ?? matches[0]

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Already addressed in ea3d60b: the fallback was removed, so the regex is no longer re-instantiated.

@dev-punia-altimate

Copy link
Copy Markdown
Contributor

🤖 Code Review — OpenCodeReview (Gemini) — 1 finding(s)

  • 1 anchored to a line (posted inline when the comment stream is on)
  • 0 without a line anchor
All findings (full text)

1. packages/drivers/src/snowflake-key.ts (L41)

[🟠 MEDIUM] Since matchAll already finds all matches in the text, you can avoid re-instantiating a new RegExp and re-scanning the string by reusing the matches array. This is more efficient and cleaner.

Suggested change:

  const matches = [...text.matchAll(PEM_BLOCK)]
  const match = matches.find((m) => /PRIVATE KEY$/.test(m[1])) ?? matches[0]

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@hkaltai

hkaltai commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

review-loop: APPROVED at 7c5c792 (reviewers: gpt-6-astra high, gpt-6.1-sol high)

@sahrizvi sahrizvi left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consensus review: APPROVE. Panel: Claude (lead) and Codex (independent pass, then a second round on each other's findings). The OpenRouter models were not used for this review.

What was checked. No live Snowflake key-pair login was made. There was no Snowflake account for this review. All keys were generated at review time with node:crypto and openssl 3.6. connect() was driven at the merge base and at the head with a fake snowflake-sdk, under Bun (the CLI's runtime). The key handed to the SDK was then checked in three ways: it passes the SDK's own isPrivateKey shape check (snowflake-sdk 2.x), it loads with crypto.createPrivateKey, and its public key matches the input key's public key.

  • Formats and variants: 15 key formats × 18 variants = 270 inputs. No input that loaded at the base fails at the head. No output has a different public key from its input. 117 inputs that failed at the base now load, including PKCS#1 without a passphrase, which the SDK rejected on main.
  • Regression set: multiline PKCS#8, \n-escaped PKCS#8, and encrypted PKCS#8 with the passphrase all give the same key at base and head.
  • Error messages: the key text, the passphrase, the normalized PEM and the OpenSSL text are never thrown, logged or returned by the new code. The decrypted key stays in memory and is passed only as privateKey with authenticator: "SNOWFLAKE_JWT". Nothing is written to disk.
  • Removed lines in snowflake.ts: they did only three things: replace literal \n, decrypt when a passphrase or ENCRYPTED was present, and pass the key through unchanged otherwise. Nothing else was dropped. Password, OAuth, externalbrowser and private_key_path behave the same as before. A private_key_path file now goes through the same normalizer, which also fixes space-joined key files.
  • Tests: packages/drivers/test passes at head (755 pass, 3 skip, 0 fail) and at base (719 pass, 0 fail). The new connect() tests fail 5 of 36 against the base driver, as the PR says.
  • Typecheck: bun run typecheck --force passes, and tsc --noEmit on packages/drivers has 0 errors.
  • Marker guard: it reports ok. packages/drivers is altimate-owned (it does not exist on upstream dev), so no markers are needed.

Remaining minors. None of them blocks; each has an inline comment:

  • Extra legacy PEM headers are folded into the body: an edge input that no common tool writes.
  • An unusable private-key block placed before a valid one: an edge input that needs two keys in one value and a passphrase.
  • A key encrypted with an empty passphrase can't be used: an edge input, and it was the same on main.
  • EC, Ed25519 and DSA keys get no local "RSA only" message: same as main, and Snowflake rejects them anyway.
  • PBE-MD5-DES gets the wrong-passphrase wording: a Node/Bun limitation, and the message still mentions an unsupported cipher.
  • Test coverage gaps: test-only.

The pre-existing key echo in connect() and the nits are in a separate PR comment.

return " "
})

const body = inner.replace(/\s+/g, "")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor (edge input, not blocking): extra legacy PEM headers end up in the base64 body. Only Proc-Type and DEK-Info are taken out before whitespace is stripped. Any other RFC 1421 header line before the blank line (for example Comment: hello) gets folded into the body, so decryption fails. Repro: an AES-256-CBC legacy PKCS#1 key with \nComment: hello inserted after DEK-Info, with the correct passphrase. Main decrypts it and returns the matching key; head throws "failed to decrypt the private key". openssl, ssh-keygen and the Snowflake docs commands never write such a header, so this is an edge case. A safe follow-up is to drop any Name: value line in the header area, not just these two.


// A pasted file may hold other blocks (certificates, public key) before the
// private key; use the first block that is a private key.
const match = [...text.matchAll(PEM_BLOCK)].find((m) => /PRIVATE KEY$/.test(m[1]))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor (edge input, not blocking): the first *PRIVATE KEY block wins even when it can't be used. If an unusable private-key block (for example -----BEGIN OPENSSH PRIVATE KEY-----) comes before a valid PKCS#8 key in the same value and a passphrase is set, main's parser skipped it and connected. Head picks the OpenSSH block and throws "could not be parsed". Without a passphrase, main also failed (the SDK only accepts text starting with -----BEGIN PRIVATE KEY-----), so only the passphrase-set case regresses. This needs two private keys pasted into one value, which is an edge case. A possible follow-up: try each private-key block in turn and keep the first one that parses.

"('-----BEGIN PRIVATE KEY-----', '-----BEGIN ENCRYPTED PRIVATE KEY-----' or '-----BEGIN RSA PRIVATE KEY-----').",
)
}
const pass = passphrase && passphrase.length > 0 ? passphrase : undefined

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor (edge input, pre-existing, not blocking): a key encrypted with an empty passphrase can't be used. passphrase: "" is treated as no passphrase, so a key encrypted with "" gets "key is encrypted; set the passphrase". crypto.createPrivateKey({ key, passphrase: "" }) would decrypt it. Main fails this case too. It is very rare.

}

try {
const keyObject = crypto.createPrivateKey({ key: normalized.pem, format: "pem", passphrase: pass })

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor (not blocking, same as main): EC (SEC1 and PKCS#8), Ed25519 and DSA keys pass here with no local message. They are converted to PKCS#8 and handed to the SDK. snowflake-sdk 2.x then signs the JWT with RS256 through jsonwebtoken, which rejects a non-RSA key, so the user never sees this module's "use an RSA key" hint. Snowflake accepts only RSA keys. A short keyObject.asymmetricKeyType !== "rsa" check with a fixed message would make this clear. I understand the reply that rejecting key types is out of scope; this is a follow-up, not a block.

const keyObject = crypto.createPrivateKey({ key: normalized.pem, format: "pem", passphrase: pass })
return keyObject.export({ type: "pkcs8", format: "pem" }).toString()
} catch {
if (encrypted) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor (Node/Bun limitation, not blocking): an unsupported encryption scheme gets the wrong-passphrase message. PKCS#8 encrypted with PBES1 PBE-MD5-DES (openssl pkcs8 -topk8 -v1 PBE-MD5-DES) cannot be decoded by Bun (BoringSSL) or Node 26 (OpenSSL 3.5, legacy provider off). The user gets "The passphrase ... is incorrect, or the key is corrupted or uses an unsupported cipher" even when the passphrase is right. The message does mention an unsupported cipher, but it does not name the scheme. Under Bun, these all decode correctly: PBES2 AES-256/AES-128/DES-EDE3, PBES1 PBE-SHA1-3DES, and legacy AES-128-CBC/AES-256-CBC/DES-EDE3-CBC. A follow-up could suggest re-encrypting with openssl pkcs8 -topk8 -v2 aes-256-cbc.


const pkcs8 = rsa.privateKey.export({ type: "pkcs8", format: "pem" }) as string
const pkcs1 = rsa.privateKey.export({ type: "pkcs1", format: "pem" }) as string
const pkcs8Enc = rsa.privateKey.export({ type: "pkcs8", format: "pem", cipher: "aes-256-cbc", passphrase: PASS }) as string

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Minor (test-only, not blocking): the fixtures cover one 2048-bit RSA key and one cipher. No test covers: extra legacy headers, an unusable private-key block before a valid one, 1024/4096-bit keys, other ciphers, or connect() with inline text that has no -----BEGIN. Mutation results: removing the quote-strip loop, or keeping spaces inside the body (removing only newlines), passes all 36 tests. Both are redundant in practice (details in the PR comment). Removing the Proc-Type/DEK-Info handling fails 6-8 tests, removing the literal-escape conversion fails 7, and taking the first PEM block of any kind fails 1.

@sahrizvi

Copy link
Copy Markdown
Collaborator

Consensus review follow-ups (Claude + Codex): items not tied to a diff line, plus nits

Pre-existing, outside this diff. Worth a follow-up, not a block for this PR: packages/drivers/src/snowflake.ts around line 601. When private_key has no -----BEGIN and is not an existing path, the error repeats the whole value: Snowflake private key: '<value>' is not a valid file path or PEM content. A user who pastes only the base64 body, or loses the BEGIN line, gets the full private-key body back in that error. The error then goes into the session transcript. Telemetry is safe here: Telemetry.maskString turns the quoted value into ?. Main behaves the same, and this PR does not touch that branch. The fix is a fixed message that leaves out the value, for example "private_key is neither PEM content nor an existing file path".

Nits

  • The quote-strip loop (snowflake-key.ts:34-36) is redundant. PEM_BLOCK matches anywhere in the text, so quotes outside the markers never reach the body. Removing the loop still passes every test, and every quoted variant still loads.
  • Removing only newlines (keeping spaces) inside the body (snowflake-key.ts:58) still loads space-joined keys under Bun, because the PEM base64 decoder skips spaces. The current tests cannot tell whether the space-join step is there.
  • A header split across lines (-----BEGIN\nPRIVATE KEY-----) or a missing END line gives "format is not recognized". That is correct, but the message could say which marker is missing.
  • The module doc (snowflake-key.ts:2-9) and the toPkcs8Pem doc list SEC1 as supported, which suggests EC keys work for Snowflake. A note that Snowflake needs RSA would help.
  • Passphrases are used exactly as given, with no trimming, which is the same as main. Leading and trailing spaces and non-ASCII passphrases work.

@hkaltai
hkaltai merged commit 2b1cbca into main Nov 19, 2026
37 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants